/**
 * 示例服务
 * 演示如何使用lifeservice框架的核心功能
 */
import ServiceRegistry from './ServiceRegistry.js';
import { LifeserviceError, ErrorType, ErrorLevel } from './ErrorService.js';
import { LogLevel } from './LoggerService.js';

class DemoService {
  constructor(options = {}) {
    this.options = {
      enabled: true,
      delay: 1000,
      ...options
    };
    
    this.serviceRegistry = null;
    this.authService = null;
    this.apiService = null;
    this.i18nService = null;
    this.notificationService = null;
    this.errorService = null;
    this.loggerService = null;
  }
  
  /**
   * 初始化服务
   */
  async boot() {
    // 获取服务注册表
    this.serviceRegistry = ServiceRegistry.getInstance();
    
    // 获取依赖的服务
    this._resolveDependencies();
    
    // 记录服务启动
    if (this.loggerService) {
      this.loggerService.info('DemoService booted', {
        enabled: this.options.enabled,
        delay: this.options.delay
      });
    }
    
    return this;
  }
  
  /**
   * 解析依赖服务
   */
  _resolveDependencies() {
    this.authService = this.serviceRegistry?.get('auth');
    this.apiService = this.serviceRegistry?.get('api');
    this.i18nService = this.serviceRegistry?.get('i18n');
    this.notificationService = this.serviceRegistry?.get('notification');
    this.errorService = this.serviceRegistry?.get('error');
    this.loggerService = this.serviceRegistry?.get('logger');
  }
  
  /**
   * 演示认证流程
   */
  async demoAuthentication() {
    if (!this.authService) {
      throw new LifeserviceError('认证服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      // 检查登录状态
      const isLoggedIn = this.authService.isAuthenticated();
      this.loggerService?.debug('当前登录状态:', { isLoggedIn });
      
      if (!isLoggedIn) {
        // 模拟登录流程演示
        this.notificationService?.info('提示', '演示登录流程：使用测试账号登录');
        
        // 这里只是演示，实际环境中应该使用真实的登录逻辑
        // await this.authService.login({ username: 'demo', password: 'demo123' });
        
        this.notificationService?.success('登录成功', '测试账号登录演示完成');
      }
      
      // 检查权限
      const permissions = [
        'user:read',
        'user:write',
        'admin:access'
      ];
      
      permissions.forEach(permission => {
        const has = this.authService.hasPermission(permission);
        this.loggerService?.info(`权限检查: ${permission} - ${has ? '已拥有' : '未拥有'}`);
      });
      
      return { success: true, isLoggedIn };
    } catch (error) {
      this.errorService?.handleError(error);
      throw error;
    }
  }
  
  /**
   * 演示API请求
   */
  async demoApiRequests() {
    if (!this.apiService) {
      throw new LifeserviceError('API服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      this.notificationService?.info('API请求演示', '开始演示不同类型的API请求');
      
      // 记录API调用开始
      this.loggerService?.debug('开始API请求演示');
      
      // 模拟API请求 - 实际使用时应该调用真实接口
      const mockRequests = [
        { method: 'get', url: '/api/demo/users' },
        { method: 'post', url: '/api/demo/users', data: { name: 'Demo User', email: 'demo@example.com' } },
        { method: 'put', url: '/api/demo/users/1', data: { name: 'Updated User' } },
        { method: 'delete', url: '/api/demo/users/1' }
      ];
      
      for (const req of mockRequests) {
        // 显示加载
        const loadingId = this.notificationService?.loading(`执行${req.method.toUpperCase()}请求: ${req.url}`);
        
        try {
          // 模拟延迟
          await new Promise(resolve => setTimeout(resolve, this.options.delay));
          
          // 在真实环境中，这里应该执行实际的API调用
          // const result = await this.apiService[req.method](req.url, req.data);
          
          this.loggerService?.info(`${req.method.toUpperCase()}请求成功: ${req.url}`);
          this.notificationService?.success('请求成功', `${req.method.toUpperCase()} ${req.url}`);
        } catch (error) {
          this.errorService?.handleError(error);
          this.notificationService?.error('请求失败', error.message || '未知错误');
        } finally {
          // 关闭加载
          if (loadingId) {
            this.notificationService?.closeLoading(loadingId);
          }
        }
        
        // 间隔延迟
        await new Promise(resolve => setTimeout(resolve, 500));
      }
      
      return { success: true, message: 'API请求演示完成' };
    } catch (error) {
      this.errorService?.handleError(error);
      throw error;
    }
  }
  
  /**
   * 演示国际化功能
   */
  async demoInternationalization() {
    if (!this.i18nService) {
      throw new LifeserviceError('国际化服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      this.notificationService?.info('国际化演示', '切换不同语言并展示翻译效果');
      
      // 获取当前语言
      const currentLocale = this.i18nService.getLocale();
      this.loggerService?.info('当前语言:', currentLocale);
      
      // 演示翻译
      const sampleKeys = ['welcome', 'login', 'logout', 'save', 'cancel'];
      sampleKeys.forEach(key => {
        const translated = this.i18nService.t(key);
        this.loggerService?.debug(`翻译: ${key} = ${translated}`);
      });
      
      // 演示切换语言
      const languages = ['en', 'zh', 'ja', 'ko'];
      
      for (const lang of languages) {
        try {
          await this.i18nService.setLocale(lang);
          this.notificationService?.success(
            '语言切换成功', 
            `当前语言: ${lang}, 欢迎: ${this.i18nService.t('welcome')}`
          );
          
          // 记录语言切换
          this.loggerService?.info(`语言切换到: ${lang}`);
          
          // 延迟
          await new Promise(resolve => setTimeout(resolve, this.options.delay));
        } catch (error) {
          this.loggerService?.warning(`语言切换失败: ${lang}`, error);
        }
      }
      
      // 恢复原语言
      await this.i18nService.setLocale(currentLocale);
      
      return { success: true, message: '国际化演示完成' };
    } catch (error) {
      this.errorService?.handleError(error);
      throw error;
    }
  }
  
  /**
   * 演示通知功能
   */
  async demoNotifications() {
    if (!this.notificationService) {
      throw new LifeserviceError('通知服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      this.loggerService?.info('开始通知功能演示');
      
      // 演示不同类型的通知
      const notifications = [
        { type: 'info', title: '信息通知', message: '这是一条普通信息通知', duration: 3000 },
        { type: 'success', title: '成功通知', message: '操作成功完成', duration: 3000 },
        { type: 'warning', title: '警告通知', message: '请注意，这是一条警告', duration: 4000 },
        { type: 'error', title: '错误通知', message: '操作失败，请重试', duration: 5000 }
      ];
      
      for (const notification of notifications) {
        this.notificationService.notify(notification);
        await new Promise(resolve => setTimeout(resolve, notification.duration + 1000));
      }
      
      // 演示确认对话框
      this.notificationService.info('确认对话框', '接下来演示确认对话框');
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const confirmed = await this.notificationService.confirm('您确定要执行此操作吗？', {
        title: '确认操作',
        okText: '确定',
        cancelText: '取消'
      });
      
      this.loggerService?.info('确认结果:', confirmed);
      this.notificationService.notify({
        type: confirmed ? 'success' : 'info',
        message: confirmed ? '您已确认操作' : '您已取消操作'
      });
      
      // 演示提示对话框
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      try {
        const inputValue = await this.notificationService.prompt('请输入您的名字:', {
          title: '信息输入',
          placeholder: '请输入姓名',
          defaultValue: '游客'
        });
        
        this.notificationService.success('输入成功', `您好，${inputValue}`);
      } catch (error) {
        this.notificationService.info('已取消输入');
      }
      
      return { success: true, message: '通知功能演示完成' };
    } catch (error) {
      this.errorService?.handleError(error);
      throw error;
    }
  }
  
  /**
   * 演示错误处理
   */
  async demoErrorHandling() {
    if (!this.errorService || !this.loggerService || !this.notificationService) {
      throw new LifeserviceError('必要服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      this.notificationService.info('错误处理演示', '演示不同类型的错误处理');
      
      // 记录演示开始
      this.loggerService.info('开始错误处理演示');
      
      // 演示不同级别的错误
      const errorTypes = [
        {
          type: ErrorType.NETWORK,
          message: '网络连接失败',
          level: ErrorLevel.ERROR,
          code: 'NETWORK_ERROR'
        },
        {
          type: ErrorType.AUTHENTICATION,
          message: '认证失败，请重新登录',
          level: ErrorLevel.ERROR,
          code: 'AUTH_FAILED'
        },
        {
          type: ErrorType.VALIDATION,
          message: '输入数据验证失败',
          level: ErrorLevel.WARNING,
          code: 'VALIDATION_ERROR'
        },
        {
          type: ErrorType.PERMISSION,
          message: '权限不足，无法执行此操作',
          level: ErrorLevel.ERROR,
          code: 'PERMISSION_DENIED'
        }
      ];
      
      for (const errorInfo of errorTypes) {
        const error = new LifeserviceError(errorInfo.message, {
          type: errorInfo.type,
          level: errorInfo.level,
          code: errorInfo.code,
          data: { timestamp: new Date().toISOString() }
        });
        
        // 记录错误
        this.loggerService.log({
          level: errorInfo.level,
          message: `演示错误: ${errorInfo.type}`,
          error: { code: errorInfo.code }
        });
        
        // 处理错误
        this.errorService.handleError(error);
        
        // 延迟
        await new Promise(resolve => setTimeout(resolve, this.options.delay));
      }
      
      // 演示未捕获错误
      this.notificationService.warning('未捕获错误演示', '接下来演示一个未捕获的Promise错误');
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 故意抛出一个未捕获的错误，将被全局错误处理器捕获
      setTimeout(() => {
        throw new Error('这是一个未捕获的错误演示');
      }, 1000);
      
      return { success: true, message: '错误处理演示完成' };
    } catch (error) {
      this.errorService.handleError(error);
      throw error;
    }
  }
  
  /**
   * 演示日志功能
   */
  async demoLogging() {
    if (!this.loggerService) {
      throw new LifeserviceError('日志服务未初始化', {
        type: ErrorType.RUNTIME,
        level: ErrorLevel.WARNING
      });
    }
    
    try {
      this.notificationService?.info('日志功能演示', '演示不同级别的日志记录');
      
      // 设置上下文
      this.loggerService.setContext({
        demo: true,
        timestamp: new Date().toISOString(),
        environment: process.env.NODE_ENV || 'development'
      });
      
      // 演示不同级别的日志
      this.loggerService.debug('这是一条调试日志', { debugInfo: '详细调试信息' });
      this.loggerService.info('这是一条信息日志', { module: 'demo' });
      this.loggerService.warning('这是一条警告日志', { warningCode: 'W001' });
      this.loggerService.error('这是一条错误日志', { 
        errorCode: 'E001',
        details: { field: 'username', reason: 'required' }
      });
      this.loggerService.critical('这是一条严重错误日志', { 
        errorCode: 'CRITICAL001',
        impact: 'system_wide' 
      });
      
      // 演示日志级别切换
      this.notificationService?.info('日志级别切换', '演示设置不同的日志级别');
      
      const levels = [LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARNING, LogLevel.ERROR, LogLevel.CRITICAL];
      
      for (const level of levels) {
        this.loggerService.setLevel(level);
        this.loggerService.info(`日志级别已切换到: ${level}`);
        
        // 测试不同级别的日志输出
        this.loggerService.debug(`当前级别 ${level} - 调试日志是否可见？`);
        this.loggerService.info(`当前级别 ${level} - 信息日志是否可见？`);
        this.loggerService.warning(`当前级别 ${level} - 警告日志是否可见？`);
        
        await new Promise(resolve => setTimeout(resolve, 500));
      }
      
      // 恢复默认级别
      this.loggerService.setLevel(LogLevel.INFO);
      this.loggerService.clearContext();
      
      return { success: true, message: '日志功能演示完成' };
    } catch (error) {
      console.error('日志演示失败:', error);
      throw error;
    }
  }
  
  /**
   * 运行完整的演示流程
   */
  async runFullDemo() {
    try {
      this.notificationService?.success('Lifeservice演示', '开始完整功能演示');
      this.loggerService?.info('开始Lifeservice框架完整演示');
      
      // 按照顺序演示各个功能
      const demos = [
        { name: 'authentication', method: this.demoAuthentication.bind(this) },
        { name: 'apiRequests', method: this.demoApiRequests.bind(this) },
        { name: 'internationalization', method: this.demoInternationalization.bind(this) },
        { name: 'notifications', method: this.demoNotifications.bind(this) },
        { name: 'errorHandling', method: this.demoErrorHandling.bind(this) },
        { name: 'logging', method: this.demoLogging.bind(this) }
      ];
      
      for (const demo of demos) {
        const loadingId = this.notificationService?.loading(`正在演示 ${demo.name}`);
        
        try {
          await demo.method();
          this.loggerService?.info(`演示 ${demo.name} 完成`);
        } catch (error) {
          this.loggerService?.error(`演示 ${demo.name} 失败`, error);
        } finally {
          if (loadingId) {
            this.notificationService?.closeLoading(loadingId);
          }
          
          // 间隔
          await new Promise(resolve => setTimeout(resolve, 1500));
        }
      }
      
      this.notificationService?.success('演示完成', 'Lifeservice框架功能演示全部完成');
      this.loggerService?.info('Lifeservice框架演示完成');
      
      return { success: true, message: '完整演示流程执行完毕' };
    } catch (error) {
      this.errorService?.handleError(error);
      throw error;
    }
  }
}

export default DemoService;